<template>
  <div class="resource-container">
    <!-- 分类和搜索区域 -->
    <el-card class="filter-card" shadow="never">
      <div class="filter-content">
        <!-- 分类区域 -->
        <div class="category-section">
          <div class="category-header">
            <el-icon class="category-icon"><Menu /></el-icon>
            <span class="category-title">资源分类</span>
          </div>
          <div class="category-tags">
            <el-tag
              v-for="(item, index) in data.resourceType"
              :key="index + 'b'"
              class="category-tag"
              :type="page.index === item.id ? 'primary' : ''"
              :effect="page.index === item.id ? 'dark' : 'plain'"
              size="large"
              @click="getTechnology(item.id)"
            >
              {{ item.name }}
              <el-badge
                v-if="item.index > 0"
                :value="item.index"
                class="tag-badge"
              />
            </el-tag>
          </div>
        </div>
        
        <!-- 搜索区域 -->
        <div class="search-section">
          <el-input
            v-model="searchWord"
            class="search-input"
            placeholder="搜索资源名称或关键词"
            :prefix-icon="Search"
            size="large"
            clearable
            @keyup.enter="getKey"
            @clear="handleClearSearch"
          />
          <el-button 
            type="primary" 
            size="large"
            class="search-button"
            @click="getKey"
          >
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 内容区域 -->
    <div class="content-wrapper">
      <el-skeleton :loading="loading" animated>
        <template #template>
          <el-row :gutter="24">
            <el-col :span="8" v-for="i in 6" :key="i">
              <el-card class="skeleton-card">
                <el-skeleton-item variant="image" style="height: 200px" />
                <div style="padding: 14px">
                  <el-skeleton :rows="3" />
                </div>
              </el-card>
            </el-col>
          </el-row>
        </template>
        
        <template #default>
          <div v-if="data.resource.length === 0" class="empty-state">
            <el-empty description="暂无资源数据">
              <el-button type="primary" @click="handleRefresh">刷新页面</el-button>
            </el-empty>
          </div>
          
          <div v-else class="resource-grid">
            <resources-card
              class="resource-item"
              :resources="item"
              v-for="(item, index) in data.resource"
              :key="index + 'r'"
            />
          </div>
          
          <!-- 加载更多 -->
          <div class="loading-section">
            <div v-if="loading2" class="loading-more">
              <el-icon class="is-loading"><Loading /></el-icon>
              <span>加载中...</span>
            </div>
            <el-divider v-else-if="end" content-position="center">
              <el-icon><Check /></el-icon>
              已加载全部内容
            </el-divider>
          </div>
        </template>
      </el-skeleton>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUpdated, reactive } from 'vue'
import { Search, Collection, Menu, Loading, Check } from '@element-plus/icons-vue'
import { Back, TweenMax } from 'gsap'
import { ElMessage } from 'element-plus'
import axios from '../utils/Axios'
import base from '../api/base'
import ResourcesCard from '../components/other/resourcesCard.vue'

const searchWord = ref('')
const loading = ref(true)
const currentDate = new Date().toDateString()
const data = reactive({
  resource: [],
  resourceType: [],
})

const page = reactive({
  beg: 0,
  end: 10,
  index: 0,
  keywords: 'null',
})

const loading2 = ref(false)
const count = ref(1)
const end = ref(false)
axios.get(base.getResource + '/0/10/0/null').then(res => {
  data.resource = res.resource
  data.resourceType = res.resourceType
  loading.value = false
})

let isMount = false
onMounted(() => {
  isMount = true
})
// let timer
onUpdated(() => {
  // if (timer) {
  //   clearTimeout(timer)
  // }
  // timer = setTimeout(() =>{
  //   if (document.getElementsByClassName('resCard')[0]) {
  //     TweenMax.staggerFrom(".resCard", 1, {opacity: 0, y: 50, ease: Back.easeOut}, 0.1);
  //   }
  // },500)
  if (isMount) {
    TweenMax.staggerFrom(
      '.item',
      1,
      { opacity: 0, x: -50, ease: Back.easeOut },
      0.3
    )
    isMount = false
  }
})

const app = document.getElementById('app')
let isRefresh = false
window.onscroll = function () {
  // 获取距离顶部的距离
  // var scrollTop = app.scrollTop;
  // 获取可视区的高度
  let windowHeight = app.clientHeight
  // 获取滚动条的总高度
  let scrollHeight = app.scrollHeight
  let my =
    document.documentElement.scrollTop ||
    document.body.scrollTop ||
    window.pageYOffset
  // console.log(my+'-'+scrollTop+'-'+windowHeight+'-'+scrollHeight)
  if (my + windowHeight >= scrollHeight - 50 && !end.value) {
    if (!isRefresh && !loading2.value) {
      isRefresh = true
      loading2.value = true
      getArticle().then(res => {
        // console.log(res.data.allArticle.length)
        data.resource = res.resource
        loading2.value = false
        isRefresh = false
        if (res.resource.length < 10 * count.value) {
          end.value = true
        }
      })
    }
  }
}
function getArticle() {
  // page.beg += 8
  page.end += 10
  count.value++
  return axios.get(
    `/resource/getResource/${page.beg}/${page.end}/${page.index}/${page.keywords}`
  )
}
function getKey() {
  loading.value = true
  page.beg = 0
  page.end = 10
  page.keywords = searchWord.value || 'null'
  count.value = 0
  end.value = false
  getArticle().then(res => {
    data.resource = res.resource
    if (res.resource.length < 10 * count.value) {
      end.value = true
    }
    loading.value = false
  })
  setTimeout(() => {
    if (document.getElementsByClassName('resCard')[0]) {
      TweenMax.staggerFrom(
        '.resCard',
        1,
        { opacity: 0, y: 50, ease: Back.easeOut },
        0.1
      )
    }
  }, 300)
}
function getTechnology(id) {
  loading.value = true
  
  // 如果点击的是当前已选中的分类，则取消选择（显示全部）
  if (page.index === id) {
    page.index = 0
  } else {
    page.index = id
  }
  
  page.beg = 0
  page.end = 10
  count.value = 0
  end.value = false
  getArticle().then(res => {
    data.resource = res.resource
    if (res.resource.length < 10 * count.value) {
      end.value = true
    }
    loading.value = false
  }).catch(error => {
    ElMessage.error('获取资源失败，请稍后重试')
    loading.value = false
  })
}

// 清空搜索
function handleClearSearch() {
  searchWord.value = ''
  getKey()
}

// 刷新页面
function handleRefresh() {
  loading.value = true
  page.beg = 0
  page.end = 10
  page.index = 0
  page.keywords = 'null'
  count.value = 1
  end.value = false
  
  axios.get(base.getResource + '/0/10/0/null').then(res => {
    data.resource = res.resource
    data.resourceType = res.resourceType
    loading.value = false
  }).catch(error => {
    ElMessage.error('刷新失败，请稍后重试')
    loading.value = false
  })
}
</script>

<style scoped lang="less">
.resource-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 80px 20px 20px 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: 100vh;
}

// 筛选卡片
.filter-card {
  margin-bottom: 20px;
  border-radius: 12px;
  border: none;
  
  :deep(.el-card__body) {
    padding: 20px 30px;
  }
}

.filter-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 32px;
}

.category-section {
  flex: 1;
}

.search-section {
  flex: 0 0 400px;
  display: flex;
  gap: 12px;
  align-items: center;
  
  .search-input {
    flex: 1;
    
    :deep(.el-input__wrapper) {
      border-radius: 12px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }
  }
  
  .search-button {
    border-radius: 12px;
    padding: 0 20px;
    white-space: nowrap;
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
    
    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4);
    }
  }
}

.category-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  
  .category-icon {
    font-size: 18px;
    color: #409eff;
  }
  
  .category-title {
    font-size: 16px;
    font-weight: 600;
    color: #2c3e50;
  }
}

.category-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  
  .category-tag {
    cursor: pointer;
    transition: all 0.3s ease;
    border-radius: 20px;
    position: relative;
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
    }
    
    .tag-badge {
      position: absolute;
      top: -8px;
      right: -8px;
    }
  }
}

// 内容区域
.content-wrapper {
  .skeleton-card {
    margin-bottom: 20px;
    border-radius: 12px;
  }
  
  .empty-state {
    text-align: center;
    padding: 60px 20px;
    background: white;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  }
  
  .resource-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));
    gap: 24px;
    
    .resource-item {
      transition: all 0.3s ease;
      
      &:hover {
        transform: translateY(-4px);
      }
    }
  }
  
  .loading-section {
    margin-top: 40px;
    text-align: center;
    
    .loading-more {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
      color: #409eff;
      font-size: 14px;
      
      .is-loading {
        animation: rotating 2s linear infinite;
      }
    }
    
    :deep(.el-divider__text) {
      color: #6c757d;
      font-size: 14px;
    }
  }
}

@keyframes rotating {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .resource-container {
    padding: 80px 16px 16px 16px;
  }
  
  .resource-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 768px) {
  .resource-container {
    padding: 70px 12px 12px 12px;
  }
  
  .filter-content {
    flex-direction: column;
    gap: 20px;
  }
  
  .search-section {
    flex: 1;
    
    .search-button {
      padding: 0 16px;
      font-size: 14px;
    }
  }
  
  .category-tags {
    gap: 8px;
  }
  
  .category-tag {
    font-size: 12px;
  }
  
  .resource-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 16px;
  }
}

@media (max-width: 480px) {
  .resource-container {
    padding: 60px 8px 8px 8px;
  }
  
  .resource-grid {
    grid-template-columns: 1fr;
    gap: 12px;
  }
}
</style>
